import sys
from confs import is_word

def output(word, rlinks, lsharp, rsharp):
    print '%s\tx' % word
    if lsharp:
        print '%s\t<' % word
    if rsharp:
        print '%s\t>' % word
    rlinks1 = set()
    for w in rlinks:
        for i in range(1, len(w) + 1):
            if is_word(w[: i]):
                rlinks1.add(w[: i])
    for w in rlinks1:
        print '%s\tl:%s' % (w, word)

def main():
    '''
    NOTE: no mapper for this job
    input: links_first.txt; words_filtered.txt
    output: links_second.txt
    (word, 'x') -> (word, 'x')
    (word, '<') -> (word, '<')
    (word, '>') -> (word, '>')
    (word, 'r:'linkee..) -> (linkee.., 'l:'word) but unifying linkee
    all above will be filtered out if (word, 'x') is not found
    '''
    prev_word = ''
    rlinks = set()
    lsharp = False
    rsharp = False
    ok = False
    for line in sys.stdin:
        line = line.strip()
        word, rest = line.split()
        if word != prev_word:
            if ok:
                output(prev_word, rlinks, lsharp, rsharp)
            rlinks = set()
            lsharp = False
            rsharp = False
            ok = False
            prev_word = word
        if rest == 'x':
            ok = True
        elif rest == '<':
            lsharp = True
        elif rest == '>':
            rsharp = True
        elif rest.startswith('r:'):
            rlinks.add(rest[2: ])
        else:
            raise RuntimeError('invalid key-value pair: %s, %s' % (word, rest))
    if ok:
        output(prev_word, rlinks, lsharp, rsharp)

if __name__ == '__main__':
    main()
